package cn.tedu.supermarket.controller;

import cn.tedu.supermarket.entity.ChangeGoods;
import cn.tedu.supermarket.entity.GoodsUser;
import cn.tedu.supermarket.mapper.GoodsMapper;
import cn.tedu.supermarket.service.GoodsImagesService;
import cn.tedu.supermarket.service.TimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;


@RestController
public class AddGoodsController {


    @Autowired
    private TimeService timeService;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsImagesService goodsImages;

    @RequestMapping("/addGoodsImages")
    public String addGoodsImages(@RequestParam("file") MultipartFile file) {
        int a = goodsImages.addGoodsImages(file);
        if (a==1){
            return "图片上传成功";
        }
        return "图片上传失败";
    }

    @RequestMapping("/addGoods")
    public String addGoods(GoodsUser goodsUser){
        goodsUser.setImgurl(goodsImages.getPaths());
        goodsUser.setAddtime(timeService.getTime());
        System.out.println(goodsUser);
        Integer a = goodsMapper.selectGoods(goodsUser.getName());
        if (a!=null){
            return "商品已添加";
        }
        int rows = goodsMapper.addGoods(goodsUser);
        if (rows>0){
            return "商品添加成功!";
        }
        return "商品添加失败";
    }

    //修改商品名字和价格
    @RequestMapping("/changeGoods")
    public ModelAndView change(int id, Model model){
        ChangeGoods changeGoods = goodsMapper.select(id);
        changeGoods.setId(id);
        System.err.println(changeGoods);
        model.addAttribute("changeGoods",changeGoods);
        return new ModelAndView("sel_user/changeGoods");
    }
    @RequestMapping("/changeGoodsMessage")
    public String changeMessage(ChangeGoods changeGoods){
        System.err.println("开始修改");
        int rows = goodsMapper.updateById(changeGoods);
        if (rows==1){
            return "修改成功";
        }
        return "修改失败";
    }
}
